package com.cxg.fairy.ec.main.order;

import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.AppCompatTextView;
import android.support.v7.widget.LinearLayoutCompat;
import android.view.View;
import android.view.ViewGroup;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cxg.fairy.app.AccountManager;
import com.cxg.fairy.delegates.LatteDelegate;
import com.cxg.fairy.ec.main.personal.address.AddressListDelegate;
import com.cxg.fairy.ec.main.personal.coupon.CouponTabDelegate;
import com.cxg.fairy.net.RestClient;
import com.cxg.fairy.net.callback.ISuccess;
import com.cxg.fairy.ui.recycler.HorizontalListView.HorizontalListAdapter;
import com.cxg.fairy.ui.recycler.HorizontalListView.HorizontalListView;
import com.cxg.fairy.ui.recycler.HorizontalListView.OrderListHorizontalImageData;
import com.cxg.fairy.util.log.LatteLogger;
import com.cxg.fairy.util.storage.LattePreference;
import com.cxg.fairy.util.toasty.Toasty;
import com.diabin.latte.ec.R;
import com.diabin.latte.ec.R2;
import com.jaredrummler.materialspinner.MaterialSpinner;

import java.util.List;
import java.util.WeakHashMap;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by Administrator on 2018/4/16.
 */

public class PostOrderDelegate extends LatteDelegate implements ISuccess {

    public static final String POST_ORDER_ID = "POST_ORDER_ID";

    public static final String POST_ORDER_ADDRESS_ID = "POST_ORDER_ADDRESS_ID";

    public static final String POST_ORDER_NAME_TEL = "POST_ORDER_NAME_TEL";

    public static final String POST_ORDER_ADDRESS = "POST_ORDER_ADDRESS";

    public static final String POST_ORDER_COUPON_NO = "POST_ORDER_COUPON_NO";

    public static final String UUID = "UUID";

    private String preSubmitOrderId = "";

    @BindView(R2.id.act_receive_name_and_tel)
    AppCompatTextView rNameTel = null;
    @BindView(R2.id.act_receive_address)
    AppCompatTextView rAddress = null;
    @BindView(R2.id.hlvSimpleList)
    HorizontalListView mHlvOrderGoodsList = null;
    @BindView(R2.id.atv_post_order_goods_count)
    AppCompatTextView oGoodsCount = null;
    @BindView(R2.id.act_post_order_coupon_count)
    AppCompatTextView oGoodsCouponValidCount = null;
    @BindView(R2.id.act_post_order_amount)
    AppCompatTextView oGoodsAmount = null;
    @BindView(R2.id.act_post_order_promotion_amount)
    AppCompatTextView oPromotionAmount = null;
    @BindView(R2.id.act_post_order_discount_amount)
    AppCompatTextView oDiscountAmount = null;
    @BindView(R2.id.act_post_order_freight)
    AppCompatTextView oGoodsFreight = null;
    @BindView(R2.id.act_post_order_discount_freight)
    AppCompatTextView oGoodsDiscountFreight = null;
    @BindView(R2.id.act_post_order_reality_amount)
    AppCompatTextView oGoodsRealityAmount = null;
    @BindView(R2.id.act_post_order_reality_amount_bottom)
    AppCompatTextView getoGoodsRealityAmountBottom = null;
    @BindView(R2.id.ms_deliver_type_spinner)
    MaterialSpinner mDeliverSpinner = null;
    @BindView(R2.id.ll_post_order_warehouse)
    LinearLayoutCompat llWarehouse = null;
    @BindView(R2.id.tv_post_order_warehouse)
    AppCompatTextView tvWarehouse = null;

    private OrderListHorizontalImageData[] mOrderListHorizontalImageData = null;

    @OnClick(R2.id.back_home)
    void onClickBackHome() {
            getSupportDelegate().pop();
    }

    /**
     * 选择收货地址
     */
    @OnClick(R2.id.ll_receive_address_list)
    void onClickAddressList() {
        getSupportDelegate().start(AddressListDelegate.create(getArguments().getInt(POST_ORDER_ADDRESS_ID),this));
    }

    /**
     * 商品清单
     */
    @OnClick(R2.id.ll_post_order_goods_list)
    void onClickOrderGoodsList() {
        getSupportDelegate().start(PostOrderGoodsListDelegate.create(getArguments().getInt(POST_ORDER_ID)));
    }

    /**
     * 优惠券列表
     */
    @OnClick(R2.id.ll_post_order_coupon_list)
    void onClickCouponList() {
        getSupportDelegate().start(CouponTabDelegate.create(getArguments().getInt(UUID),preSubmitOrderId,this));
    }

    /**
     * 确认订单-收银台
     */
    @OnClick(R2.id.act_post_order_pay_type)
    void onClickToCheckPay() {

        RestClient.builder()
                .url("placeOrder")
                .params("uuid",AccountManager.getSignUUID())
                .loader(getContext())
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        int code = JSON.parseObject(response).getInteger("code");
                        if (code == 1) {
                            String orderNo = JSON.parseObject(response).getJSONObject("data").getString("orderNo");
                            getSupportDelegate().startWithPop(new CheckPayDelegate().setIsDeposit(false).setOrderNo(orderNo));
                        } else {
                            Toasty.warning(getContext(),"购物车订单提交失败!").show();
                        }
                    }
                })
                .build()
                .post();
    }

    public static PostOrderDelegate create(WeakHashMap argsMap) {
        final Bundle args = new Bundle();
            args.putString(POST_ORDER_COUPON_NO, String.valueOf(argsMap.get("POST_ORDER_COUPON_NO")));
        if (argsMap.get("POST_ORDER_ADDRESS_ID") == null) {
        } else {
            args.putInt(POST_ORDER_ADDRESS_ID, (Integer) argsMap.get("POST_ORDER_ADDRESS_ID"));
        }
            args.putString(POST_ORDER_NAME_TEL, String.valueOf(argsMap.get("POST_ORDER_NAME_TEL")));
            args.putString(POST_ORDER_ADDRESS, String.valueOf(argsMap.get("POST_ORDER_ADDRESS")));
        final PostOrderDelegate delegate = new PostOrderDelegate();
        delegate.setArguments(args);
        return delegate;
    }


    @Override
    public Object setLayout() {
        return R.layout.delegate_post_order;
    }

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        initData();
        mDeliverSpinner.setItems(getResources().getStringArray(R.array.post_order_deliver_types));
    }

    @Override
    public void onSuccess(String response) {
        String receiveNameTel =  LattePreference.getCustomAppProfile(POST_ORDER_NAME_TEL);
        String receiveAddress =  LattePreference.getCustomAppProfile(POST_ORDER_ADDRESS);
        String couponNoSelected = LattePreference.getCustomAppProfile(POST_ORDER_COUPON_NO);

        final JSONArray jsonArray = JSON.parseObject(response).getJSONArray("data");
        JSONObject obj = (JSONObject) jsonArray.get(0);

        //配送方式
        mDeliverSpinner.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
            @Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
                //Snackbar.make(view, "Clicked " + item, Snackbar.LENGTH_LONG).show();
                initDataByDeliver(position+1);
                ViewGroup.LayoutParams lp;
                lp = llWarehouse.getLayoutParams();
                lp.height = position == 2 ? 35 : 0;
                llWarehouse.setLayoutParams(lp);
            }
        });


        LatteLogger.e("response=",response);

        if (receiveNameTel != null && !"".equals(receiveNameTel)) {
            rNameTel.setText(receiveNameTel);
        } else {
            rNameTel.setText(String.valueOf(obj.get("receive_name")) + "  " + String.valueOf(obj.get("receive_tel")));
        }

        if (receiveAddress != null && !"".equals(receiveAddress)) {
            rAddress.setText(receiveAddress);
        } else {
            rAddress.setText(String.valueOf(obj.get("receive_address")));
        }

        tvWarehouse.setText(obj.getString("warehouse_address"));

        oGoodsCount.setText("共" + obj.get("orderCount").toString() + "件");

        oGoodsAmount.setText(obj.get("orderAmount").toString());
        oPromotionAmount.setText(obj.get("orderPromotionAmount").toString());
        oDiscountAmount.setText(obj.get("orderDiscountAmount").toString());
        oGoodsFreight.setText(obj.get("orderFreight").toString());
        oGoodsDiscountFreight.setText(obj.get("orderDiscountFreight").toString());
        oGoodsRealityAmount.setText(obj.get("orderRealityAmount").toString());
        getoGoodsRealityAmountBottom.setText(obj.get("orderRealityAmount").toString());
        preSubmitOrderId = obj.getString("preSubmitOrderId");
        obj.getString("warehouse_address");

        List imgList = (List) obj.get("goodsList");
        int size = imgList.size();
        mOrderListHorizontalImageData = new OrderListHorizontalImageData[size];
        for (int i = 0; i < imgList.size(); i++) {
            mOrderListHorizontalImageData[i] = new OrderListHorizontalImageData(Color.RED, "Red", imgList.get(i).toString());
        }

        HorizontalListAdapter adapter = new HorizontalListAdapter(getContext(), mOrderListHorizontalImageData);
        mHlvOrderGoodsList.setAdapter(adapter);

        if (couponNoSelected != null && couponNoSelected!="null" && !"".equalsIgnoreCase(couponNoSelected)) {
            oGoodsCouponValidCount.setText(couponNoSelected);
            oGoodsCouponValidCount.setTextColor(Color.BLACK);
            oGoodsCouponValidCount.setBackgroundColor(Color.WHITE);
            oGoodsCouponValidCount.setText(String.format(getResources().getString(R.string.post_order_coupon_selected)));
        } else {
            oGoodsCouponValidCount.setBackgroundColor(Color.RED);
            oGoodsCouponValidCount.setTextColor(Color.WHITE);
            oGoodsCouponValidCount.setText(String.format(getResources().getString(R.string.post_order_coupon_init),(Integer)obj.get("orderCouponValidCount")));
        }
    }

    private void initDataByDeliver(int i) {
        RestClient.builder()
                .url("shopCart/settleAccount")
                .params("uuid", AccountManager.getSignUUID())
                .params("distriModeId",i)
                .success(this)
                .build()
                .post();
    }

    private void initData() {
        RestClient.builder()
                .loader(getContext())
                .url("shopCart/settleAccount")
                .params("uuid", AccountManager.getSignUUID())
                .success(this)
                .build()
                .post();
    }

}
